import os
import pandas as pd
from function.merger import rrdata_deal

# 指定要读取的目录
directory = r'D:\学习&科研\华为手表项目\华为数据\规律跑者'

# 储存runner的记录
runner_time_check = pd.DataFrame(columns=['runner', 'date', 'startime','endtime','HR_avg'])

# 遍历指定的文件夹
folders_to_read = ['data', 'rrdata']
for folder in os.listdir(directory):
    print(folder)
    runnerfolder = os.path.join(directory, folder, 'rrdata')

    if os.path.isdir(runnerfolder):
        for runner_record in os.listdir(runnerfolder):
            if folder==runner_record[0:4]:
                runner_record_csv = os.path.join(runnerfolder, runner_record)
                df = rrdata_deal(runner_record_csv)

                if df.empty:
                    print(f"警告: {runner_record_csv} 是空的，跳过此文件。")
                    pass
                # print(df.columns)
                # 获取第一行和最后一行
                else:
                    first_row = df.iloc[0]
                    last_row = df.iloc[-1]

                    start_time = pd.to_datetime(pd.to_numeric(first_row['timestamp']), unit='ms').tz_localize('UTC').tz_convert('Asia/Shanghai')
                    end_time = pd.to_datetime(pd.to_numeric(last_row['timestamp']), unit='ms').tz_localize('UTC').tz_convert('Asia/Shanghai')
                    duration = end_time - start_time
                    duration_minutes =int( duration.total_seconds() / 60)
                    if duration_minutes>0:

                        start_hour = start_time.hour  # 提取小时
                        start_minute = start_time.minute  # 提取分钟

                        # 将小时和分钟组合成字符串格式 (如 "HH:MM")
                        start_time_str = f"{start_hour:02}:{start_minute:02}"
                        # print(folder,start_time.date(),runner_record[5:18],duration_minutes,start_time_str)
                        print(f'文件名{runner_record},开始时间{start_time.strftime("%H:%M:%S")},结束时间{end_time.strftime("%H:%M:%S")}')
                        # print(df)
                        # 先将HR列转换为数值类型，处理非数值数据
                        df['HR'] = pd.to_numeric(df['HR'], errors='coerce')

                        hr_avg = df['HR'].mean()
                        new_data = pd.DataFrame({
                            'runner': [folder],
                            'date': [start_time.date()],
                            'startime':[start_time.strftime("%H:%M:%S")],
                            'endtime': [end_time.strftime("%H:%M:%S")],
                            'HR_avg': [int(hr_avg)]
                        })

                        # 使用pd.concat合并DataFrame
                        runner_time_check = pd.concat([runner_time_check, new_data], ignore_index=True)
# runner_time_check = runner_time_check.groupby(['runner', 'date'], as_index=False).agg({
#     # 'difftime': lambda x: list(x),
#     'startime': lambda x: list(x),
#     'endtime': lambda x: list(x),
#     'HR_avg': lambda x: list(x)
# })
# 输出时间差列表

print(runner_time_check)